<?php

namespace app\api\index\v1\controller;

use app\api\index\v1\service\PassportService;
use app\library\BaseController;
use app\provider\SmsProvider;
use zhanshop\App;
use zhanshop\server\Request;
use zhanshop\server\Response;

class Passport extends BaseController
{
    /**
     * @api POST login 用户登录
     * @apiParam string channel 渠道
     * @apiParam string type 登陆类型（可选值：phone，wechat，umeng）
     * @apiParam json data 登陆数据
     * @apiGroup 用户模块
     * @apiDescription
     */
    public function login(Request $request, Response $response){
        $data = $request->validateRule([
            'channel' => 'required',
            'type' => 'required | string',
            'data' => 'required | array',
        ])->getData();
        $login = $data['type'].'Login';
        $appData = [
            'app' => $this->getApp($request),
            'channel' => $data['channel'],
            'ip' => $request->realIp()
        ];
        $result = App::make(PassportService::class)->$login($appData, $data['data']);
        return $this->result($result);
    }

    /**
     * @api POST regBind 注册绑定
     * @apiHeader string token 用户token
     * @apiParam string channel 渠道
     * @apiParam string area 地区代码如：+86
     * @apiParam string phone 手机号码
     * @apiParam string code 短信验证码
     * @apiParam json data 登陆数据
     * @apiGroup 用户模块
     * @apiDescription
     */
    public function regBind(Request $request, Response $response)
    {
        $token = $request->header("token");
        $data = $request->validateRule([
            'channel' => 'required',
            'area' => 'required | string',
            'phone' => 'required | string',
            'code' => 'required | string',
        ])->getData();
        $appData = [
            'app' => $this->getApp($request),
            'channel' => $data['channel'],
            'ip' => $request->realIp()
        ];
        $result = App::make(PassportService::class)->regBind($appData, $token, $data);
        return $this->result($result);
    }

    /**
     * @api POST smscode 发验证码
     * @apiParam string area 地区代码如：+86
     * @apiParam string phone 手机号码
     * @apiParam string type 短信类型（login:登录短信，register:注册短信，bind：手机号绑定，unbind：解除手机号绑定）
     * @apiGroup 用户模块
     * @apiMiddleware \zhanshop\server\middleware\IpLimitAuth::class
     * @apiDescription
     */
    public function smscode(Request $request, Response $response)
    {
        $data = $request->validateRule([
            'area' => 'required | string',
            'phone' => 'required | json',
            'type' => 'required',
        ])->getData();
        $type = $data['type'];
        $result = App::make(SmsProvider::class)->$type($this->getApp($request), $data['area'], $data['phone']);
        return $this->result($result);
    }
}